package com.asia5b.a5mall.home.activity

import android.graphics.BitmapFactory
import android.text.TextUtils
import android.view.View
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.asia5b.a5bmall.resource.ActCons
import com.asia5b.a5bmall.umeng.logic.UmengShare
import com.asia5b.a5mall.home.R
import com.asia5b.a5mall.home.adapter.SettingItemAdapter
import com.asia5b.a5mall.home.databinding.ActivitySettingBinding
import com.asia5b.a5mall.middleware.api.TokenManager
import com.asia5b.a5mall.middleware.base.BaseApplication
import com.asia5b.a5mall.middleware.base.SimpleActivity
import com.asia5b.a5mall.middleware.config.CountrysRepository
import com.asia5b.a5mall.middleware.config.UserRepository
import com.asia5b.a5mall.middleware.event.LogoutEvent
import com.asia5b.a5mall.middleware.event.ModifyMobileEvent
import com.asia5b.a5mall.middleware.logic.viewmodel.setting.SettingVM
import com.asia5b.a5mall.middleware.model.bean.SettingItemBean
import com.asia5b.a5mall.middleware.model.member.CountryModel
import com.asia5b.a5mall.middleware.model.member.CurrencyModel
import com.asia5b.a5mall.middleware.utils.*
import com.asia5b.a5mall.middleware.widget.CancelSureViewModel
import io.reactivex.android.schedulers.AndroidSchedulers
import kotlinx.android.synthetic.main.activity_setting.*
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/**
 * Created by zhangyuncai on 2019/12/21.
 */
@Route(path = ActCons.SettingActivity)
class SettingActivity : SimpleActivity<SettingVM, ActivitySettingBinding>() {
    override var sIsDark = true
    val settingList = arrayListOf<SettingItemBean>()
    lateinit var settingItemAdapter: SettingItemAdapter

    override val viewModelClazz: Class<SettingVM>
        get() = SettingVM::class.java

    override fun getDataBinding(): ActivitySettingBinding {
        return ActivitySettingBinding.inflate(layoutInflater)
    }


    override fun initView() {
        setItemsView()
    }

    fun setUserView() {
        if (UserRepository.isLogin()) {
            val userInfo = UserRepository.getUserInfo()
            mDataBinding.data = userInfo
            setting_username_tv.setText("${getString(R.string.用户名)}:${userInfo.username}")
            WImageLoader.displayImage(userInfo.face, setting_userface_iv, R.drawable.ic_userface)
        } else {
            mDataBinding.data = null
            setting_username_tv.setText("${getString(R.string.登录)}/${getString(R.string.注册)}")
            setting_userface_iv.setImageResource(R.drawable.ic_userface)
        }
    }

    fun setItemsView() {

        settingList.clear()

        setUserView()

        var settingItemBean = SettingItemBean()
        settingItemBean.name = getString(R.string.地址管理)
        settingItemBean.hasDivider1 = true

        settingItemBean.onClickListener = View.OnClickListener {
            push(ActCons.AddressListActivity, isNeedLogin = !UserRepository.isLogin())
        }
        if (UserRepository.isLogin()) {
            settingList.add(settingItemBean)
        }

        settingItemBean = SettingItemBean()
        settingItemBean.name = getString(R.string.账户安全)
        settingItemBean.hasDivider2 = true
        settingItemBean.onClickListener = View.OnClickListener {
            push(ActCons.MemberSecurityActivity)
        }
        if (UserRepository.isLogin()) {
            settingList.add(settingItemBean)
        }

        if (false) {
            settingItemBean = SettingItemBean()
            settingItemBean.name = getString(R.string.支付设置)
            settingItemBean.hasDivider2 = true
            settingItemBean.onClickListener = View.OnClickListener {

            }
            if (UserRepository.isLogin()) {
                settingList.add(settingItemBean)
            }
        }

        if (false) {
            settingItemBean = SettingItemBean()
            settingItemBean.name = getString(R.string.setting_zizhi)
            settingItemBean.content = getString(R.string.setting_zizhi_add)
            settingItemBean.hasDivider1 = true
            settingItemBean.onClickListener = View.OnClickListener {
                if (UserRepository.isLogin(mActivity)) {
                    push(ActCons.AddCertActivity)
                }
            }
            if (UserRepository.isLogin()) {
                settingList.add(settingItemBean)
            }
        }

        settingItemBean = SettingItemBean()
        settingItemBean.name = getString(R.string.语言选择)
        settingItemBean.hasDivider2 = true
        settingItemBean.onClickListener = View.OnClickListener {
            push(ActCons.ChoiceLanguageActivity)
        }
        val appLanguage = LocalManageUtil.getAppLanguage()
        when (appLanguage) {
            LocalManageUtil.LANGUAGE_CN -> {
                settingItemBean.content = getString(R.string.中文)
            }
            LocalManageUtil.LANGUAGE_SU -> {
                settingItemBean.content = getString(R.string.印尼文)
            }
            LocalManageUtil.LANGUAGE_MS -> {
                settingItemBean.content = getString(R.string.马来文)
            }
            LocalManageUtil.LANGUAGE_VI -> {
                settingItemBean.content = getString(R.string.越南文)
            }
            LocalManageUtil.LANGUAGE_TH -> {
                settingItemBean.content = getString(R.string.泰文)
            }
            else -> {
                settingItemBean.content = getString(R.string.英文)
            }
        }
        settingList.add(settingItemBean)

        settingItemBean = SettingItemBean()
        settingItemBean.name = getString(R.string.国家公馆)
        settingItemBean.hasDivider2 = true
        settingItemBean.onClickListener = View.OnClickListener {
            push(ActCons.ChoiceCountryActivity)
        }
        settingList.add(settingItemBean)

        settingItemBean = SettingItemBean()
        settingItemBean.name = getString(R.string.币种选择)
        settingItemBean.hasDivider1 = true
        settingItemBean.onClickListener = View.OnClickListener {
            push(ActCons.ChoiceCurrencyActivity)
        }
        settingList.add(settingItemBean)

        settingItemBean = SettingItemBean()
        settingItemBean.name = getString(R.string.应用分享)
        settingItemBean.content = getString(R.string.应用引流)
        settingItemBean.hasDivider2 = true
        settingItemBean.onClickListener = View.OnClickListener {
            UmengShare.Init(mActivity.weak().get())
                    .web("http://47.88.223.5:5000/")
                    .setWebTitle(String.format(getString(R.string.应用下载), getString(R.string.appname)))
                    .setWebImage(BitmapFactory.decodeResource(BaseApplication.sApplication.resources, R.mipmap.ic_launcher))
                    .setWebDescription(getString(R.string.appname))
                    .webShare()
        }
        settingList.add(settingItemBean)

        settingItemBean = SettingItemBean()
        settingItemBean.name = getString(R.string.清除缓存)
        settingItemBean.hasDivider2 = true
        settingItemBean.onClickListener = View.OnClickListener {
            CancelSureViewModel(mActivity, R.string.确认清除缓存内容) {
                mViewModel.clearChche(mActivity)
            }.show()
        }
        settingList.add(settingItemBean)

        settingItemBean = SettingItemBean()
        settingItemBean.name = getString(R.string.关于我们)
        settingItemBean.content = "V${AppUtil.getVersionName()}"
        settingItemBean.hasDivider1 = true
        settingItemBean.onClickListener = View.OnClickListener {
            push(ActCons.AboutActivity)
        }
        settingList.add(settingItemBean)

        settingItemAdapter = SettingItemAdapter(settingList)
        rv_setting.run {
            layoutManager = LinearLayoutManager(mActivity)
            adapter = settingItemAdapter
        }
        rv_setting.isFocusable = false
        rv_setting.isFocusableInTouchMode = false


        CountrysRepository.anyCallback<ArrayList<CountryModel>>({
            var currentCountryName = ""
            for (countryModel in it) {
                if (countryModel.country_id == appCountrySelect) {
                    dddLog("当前选中的国家公馆:${countryModel.country_name}")
                    currentCountryName = countryModel.country_name
                    break
                }
            }
            for ((index, settingItemBean) in settingList.withIndex()) {
                if (TextUtils.equals(settingItemBean.name, getString(R.string.国家公馆))) {
                    settingItemBean.content = currentCountryName
                    settingItemAdapter.notifyItemChanged(index)
                    break
                }
            }
        }, CountrysRepository.country)

        CountrysRepository.anyCallback<ArrayList<CurrencyModel>>({ currency_list ->
            var select_currency = CountrysRepository.getCurrencySelect()
            var currentCurrencyName = ""
            for (currencyModel in currency_list) {
                if (select_currency.country_id == currencyModel.country_id) {
                    dddLog("当前币种:${currencyModel.currency_name}")
                    currentCurrencyName = currencyModel.currency_name
                    break
                }
            }
            for ((index, settingItemBean) in settingList.withIndex()) {
                if (TextUtils.equals(settingItemBean.name, getString(R.string.币种选择))) {
                    settingItemBean.content = currentCurrencyName
                    settingItemAdapter.notifyItemChanged(index)
                    break
                }
            }
        }, CountrysRepository.currency)

    }


    override fun initEvent() {
        setting_action_userinfo.setOnClickListener {
            if (UserRepository.isLogin(mActivity)) {
                push(ActCons.PersonInfoActivity)
            }
        }
        tv_setting_logout.setOnClickListener {
            CancelSureViewModel(mActivity).apply {
                leftStringRes = R.string.确定
                rightStringRes = R.string.取消
                contentStringRes = R.string.确定要退出登录吗
                leftClick = {
                    TokenManager(mActivity).getUid()?.more { uid ->
                        mViewModel.logout(uid)
                    }
                }
            }.show()
        }
    }

    override fun initData() {
        UserRepository.getUserInfoOB()
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe {
                    setItemsView()
                }
        mViewModel.getCacheSize(mActivity)

    }

    override fun startObserver() {
        mViewModel.logoutLiveData.observe(this, Observer {
            showMessage(getString(R.string.退出登录成功))
            setUserView()
            getEventBus().post(LogoutEvent())
            ARouter.getInstance().build(ActCons.MainActivity).navigation()
            pop()
        })
        mViewModel.clearChcheLiveData.observe(this, Observer { size ->
            for (bean in settingList) {
                if (TextUtils.equals(bean.name, getString(R.string.清除缓存))) {
                    bean.content = size
                    settingItemAdapter.notifyDataSetChanged()
                    break
                }
            }
        })
    }

    override val isRegisterEventBus: Boolean
        get() = true

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onModifyMobileEvent(event: ModifyMobileEvent) {
        //            pop()
    }

}